﻿module Sustainalytics.ProductInvolvement.Admin {

    import Common = Sustainalytics.Common;
    import CommonAdmin = Sustainalytics.Common.Admin;
    import Routing = Sustainalytics.Routing;

    export class PIInputFileController {

        // controller scope
        public $scope: ng.IScope;
        // services
        private $q: ng.IQService;
        private $location: ng.ILocationService;
        private $routeParams: any;
        private notificationFactory: Common.INotificationFactory;
        private backendService: PIBackendService;
        private staticObjectsAdmin: CommonAdmin.IStaticObjects;

        // specifies whether current controller is in loading state
        public isLoading: boolean;
        public latestStatus: string;
        public isFileScheduled: boolean;
        public latestDetails: string;
        public uploadProgress: number;

        private inputFile: PIInputFileDto;
        private selectedFile: File;
        
        constructor(
            $scope: ng.IScope,
            $q: ng.IQService,
            $location: ng.ILocationService,
            private RoutingService: Routing.IRoutingService,
            backend: PIBackendService,
            notificationFactory: Common.INotificationFactory,
            staticObjectsAdmin: CommonAdmin.IStaticObjects) {

            var ctx = this;

            ctx.$scope = $scope;
            ctx.$q = $q;
            ctx.$location = $location;
            ctx.backendService = backend;
            ctx.notificationFactory = notificationFactory;
            ctx.staticObjectsAdmin = staticObjectsAdmin;
            ctx.$routeParams = RoutingService.getRouteParams();


            ctx.uploadProgress = -1; 
            ctx.isFileScheduled = false;
            ctx.latestStatus = 'No upload task scheduled';
            ctx.latestDetails = "";

            // load status
            ctx.updateStatus();

            // scope
            $scope['productinvolvement'] = ctx;
            // notify parents that the controller was created
            $scope.$emit('productinvolvement.created', ctx);
        }

        // excel selection
        public onSelectExcel(files): any {

            var ctx = this;

            ctx.selectedFile = null;
            var file = files[0]; // html assures is just 1
            if (file && (file.type != "application/vnd.ms-excel" && file.type != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
                ctx.showErrorCode(2200);
            }
            else if (file) {

                ctx.selectedFile = file;
            }
        }

        // excel upload
        public uploadInputFile() {
            var ctx = this;
            if (ctx.selectedFile)
            {
                ctx.uploadProgress = 0;
                var promise = ctx.backendService.uploadPIInputFile(ctx.selectedFile, ctx.uploadProgress);
                promise            
                    .then(
                        // success 
                        (data: { id: string; isvalid: boolean; details: string; hasMissingUniverseSheet: boolean; hasMissingUniverseSheetData: boolean }) => {
                        
                                // handles  validation /operation result
                                ctx.$scope.$evalAsync(() => {
                                    console.log(data);

                                    ctx.isFileScheduled = data.isvalid && !data.hasMissingUniverseSheet && !data.hasMissingUniverseSheetData;
                                    ctx.latestDetails = data.details;

                                    if (data.isvalid)
                                    {
                                        ctx.notificationFactory.success('Upload succeeded. Data in file is valid.');
                                    }
                                    else
                                    {  
                                        if (data.hasMissingUniverseSheet || data.hasMissingUniverseSheetData)
                                        {
                                            ctx.notificationFactory.error('', 'No task scheduled. PI Universe sheet missing, or no data available in this sheet.');
                                        }
                                        else
                                        {
                                            ctx.notificationFactory.success('Upload succeeded. Some data did not pass validation and it will be ignored for synchronization.');
                                        }
                                    }
                                        
                                    ctx.updateStatus();
                                    ctx.uploadProgress = -1;
                                });
                            },
                            //error
                            (data: { code: number /*todo: only upload failure, invalid file is a success */ }) => 
                            {
                                ctx.showErrorCode(2300);       
                                ctx.updateStatus();
                                ctx.uploadProgress = -1;
                            }
                    );
            }
        }

        // cancel last update
        public cancelLastInputFile() {

            console.log("cancelLastInputFile");
            var ctx = this;
            if (ctx.inputFile && ctx.inputFile.id) {
                ctx.backendService.cancelLastInputFile(ctx.inputFile.id)
                    .finally(() => {
                        
                        ctx.latestDetails = "";
                        ctx.selectedFile = null;
                        ctx.updateStatus();

                        $("input[type='file']").val('');
                    });

                
            }
        }

        private updateStatus(){// handles always visible status

            var ctx = this;
            ctx.isLoading = true;
            var promise = ctx.backendService.getLatestStatus();
            promise.then(
                (response) =>
                {       
                    var inputFile        = <PIInputFileDto>response.data;              
                    ctx.latestStatus    = ctx.backendService.composeStatus(inputFile);
                    ctx.inputFile       = inputFile;
                    ctx.isFileScheduled = inputFile && (inputFile.history[inputFile.history.length - 1].status == PIUploadStatus.UploadValid);                                        
                }, 
                (failureReason) =>
                {

                })
                .finally(() => { ctx.isLoading = false; });                        
        }       


        // show error code
        // TO DO: staticObjects has dependency on notificationFactory but notificationFactory is used to send messages
        // notificationFactory should use staticObjects to write messages based on provided codes which messages can be located into staticObjects.
        // In this case we cannot do cyclic references and therefore this method was created.
        private showErrorCode(code: number) {
            var ctx = this;
            var msg = ctx.staticObjectsAdmin.getMessageByInternalCode(code);
            ctx.notificationFactory.error('', msg);
        }
    }


    // register controller with News Angular module
    var mod = angular.module(piAdminModuleName);

    mod.controller('PIInputFileController',
        ['$scope', '$q', '$location', 'RoutingService', 'PIBackendService', 'notificationFactory', 'staticObjectsAdmin', PIInputFileController]);
}